package com.demo.security.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.IMessageConstants;
import com.demo.ex.ServiceException;
import com.demo.security.mapper.UserMapper;
import com.demo.security.model.SysUser;
import com.demo.security.service.UserService;
import com.demo.security.util.JwtTokenUtil;
import com.demo.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.assertj.core.internal.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service("UserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    private UserCacheServiceImpl userCacheService;

    @Override
    public List<SysUser> getUser() {
        return userMapper.getUser();
    }
    @Override
    public SysUser getUserByName(String name) {
        SysUser sysUser = userCacheService.getSysUserByName(name);
        if (null == sysUser) {
            sysUser =  userMapper.getUserByName(name);
        }
        sysUser = Optional.ofNullable(sysUser).orElseThrow(() -> new ServiceException("用户信息为空"));
        return sysUser;
    }

    @Override
    public SysUser getUserByCode(String userCode) {
        SysUser sysUser = userCacheService.getSysUserByCode(userCode);
        if (null == sysUser) {
            sysUser =  userMapper.getuserByCode(userCode);
        }
        sysUser =  Optional.ofNullable(sysUser).orElseThrow(() -> new ServiceException("用户信息为空"));
        return sysUser;
    }

    @Override
    public String getCurrentUserCode() {
        String userCode = null;
        try {
            HttpServletRequest request = HttpUtil.getRequest();
            if (request != null) {
                //构建OAuth资源请求
                OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request);
                //获取Access Token
                String accessToken = oauthRequest.getAccessToken();
                userCode = JwtTokenUtil.getCodeFromToken(accessToken);
            }
        } catch (OAuthProblemException e) {
            //log.error(IMessageConstants.EXCEPTION_LOG, e);
        } catch (Exception e) {
            log.error(IMessageConstants.EXCEPTION_LOG, e);
        }
        return userCode;
    }

    @Override
    public String getLoginName(String userCode) {
        SysUser sysUser = getUserByCode(userCode);
        return sysUser.getUsername();
    }
}
